<template>

    <div class="user-profile-container">
        <!-- 菜单面板 -->
        <div class="menu-panel">
            <a-menu style="border: 2px solid #e6f4ff; border-radius: 10px;">
                <a-menu-item key="1" @click="currentPanel = 'info'">
                    <IdcardTwoTone style="font-size: 16px; margin: 0 7px;" />个人信息
                </a-menu-item>
                <a-menu-item key="2" @click="currentPanel = 'favorites'">
                    <StarTwoTone style="font-size: 18px; margin: 0 7px;" />收藏夹
                </a-menu-item>
                <a-menu-item key="3" @click="currentPanel = 'myPosts'">
                    <MessageTwoTone style="font-size: 16px; margin: 0 7px; " />我的发布
                </a-menu-item>
            </a-menu>
        </div>
        <!-- 个人信息面板 -->
        <div class="info-panel" v-if="currentPanel === 'info'">
            <div class="user-avatar" :style="avatarStyle">
                {{ userInfo.name[0] }}
            </div>
            <a-form :model="userInfo" layout="horizontal" class="user-form">
                <a-form-item label="用户名">
                    <a-input v-model:value="userInfo.name" :style="{ width: '150px' }" disabled />
                </a-form-item>
                <a-form-item label="性别">
                    <a-select v-model:value="userInfo.gender" :style="{ width: '60px' }" :disabled="!isEditing">
                        <a-select-option v-for="option in genderOptions" :key="option.value" :value="option.value">
                            {{ option.label }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="年龄">
                    <a-input-number v-model:value="userInfo.age" :style="{ width: '60px' }" :disabled="!isEditing" />
                </a-form-item>
                <a-form-item label="信用等级">
                    <a-rate v-model:value="userInfo.creditLevel" allow-half disabled />
                </a-form-item>
                <a-form-item label="收货地址">
                    <a-textarea v-model:value="userInfo.address" :disabled="!isEditing" :rows="2" style="resize: none;"/>
                </a-form-item>
                <a-form-item label="个性签名">
                    <a-textarea v-model:value="userInfo.signature" :disabled="!isEditing" :rows="4" style="resize: none;" />
                </a-form-item>
            </a-form>
            <!-- 编辑按钮 -->
            <div class="edit-button">
                <a-button @click="toggleEditMode" v-if="!isEditing" style="color: #1890ff;">
                    <EditTwoTone />编辑信息
                </a-button>
                <a-button type="primary" @click="submitEdits" v-else>
                    <CheckSquareTwoTone />提交修改
                </a-button>
            </div>
        </div>
        <!-- 收藏夹面板 -->
        <div class="favorites-panel" v-if="currentPanel === 'favorites'">
            <h2>收藏夹</h2>
            <!-- 收藏夹内容 -->
        </div>
        <!-- 我的发布面板 -->
        <div class="my-posts-panel" v-if="currentPanel === 'myPosts'">
            <h2>我的发布</h2>
            <!-- 我的发布内容 -->
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { EditTwoTone, CheckSquareTwoTone, StarTwoTone, MessageTwoTone, IdcardTwoTone } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

const isEditing = ref(false);
const currentPanel = ref('info');

const genderOptions = ref([
    { value: '男', label: '男' },
    { value: '女', label: '女' },
]);

const userInfo = ref({
    name: '',
    gender: '',
    age: 0,
    address: '',
    signature: '',
    creditLevel: 0,
});

const avatarStyle = {
    backgroundColor: 'blue',
    color: 'white',
    borderRadius: '50%',
    width: '80px',
    height: '80px',
    lineHeight: '80px',
    textAlign: 'center',
    fontSize: '24px',
    margin: '20px 0',
};

function toggleEditMode() {
    isEditing.value = !isEditing.value;
};

async function submitEdits() {
    // 收集表单数据
    const formData = {
        gender: userInfo.value.gender,
        age: userInfo.value.age,
        shipping_address: userInfo.value.address,
        personal_signature: userInfo.value.signature,
    };

    // 使用 fetch 发送请求到服务器
    fetch('/api/updateuserinfo', {
        method: 'PUT',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token'),
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            message.success('用户信息更新成功！');
            //console.log('请求成功，用户信息更新！', data);
        })
        .catch(error => {
            message.error('请求失败，无法更新用户信息！');
            // console.error('请求失败，无法更新用户信息', error);
        })
        .finally(() => {
            // 无论请求成功还是失败，都应该将编辑模式重置为 false
            isEditing.value = false;
        });

};

const fetchData = () => {
    fetch('/api/userinfo', {
        method: 'get',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token'),
            'Content-Type': 'application/json',
        },
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            console.log('用户信息：', data);
            // 更新用户信息
            userInfo.value.name = data.data.username;
            userInfo.value.gender = data.data.gender;
            userInfo.value.age = data.data.age;
            userInfo.value.address = data.data.shipping_address;
            userInfo.value.signature = data.data.personal_signature;
            userInfo.value.creditLevel = data.data.credit_rating;
        })
        .catch(error => {
            // 处理请求错误
            console.error('请求失败，无法获取用户信息', error);
            localStorage.removeItem('username');
            localStorage.removeItem('token')
            message.error('登录状态失效！');
            // 跳转到其他页面
            setTimeout(() => {
                window.location.href = '/login';
            }, 2000);
        });
};

onMounted(async () => {
    fetchData();
});
</script>

<style scoped>
.user-profile-container {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    margin: 0 auto;
    padding-top: 10px;
    width: 1000px;
}

.menu-panel {
    width: 200px;
    border-radius: 10px;
    margin-right: 10px;
}

.info-panel,
.favorites-panel,
.my-posts-panel {
    border: 2px solid #e6f4ff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 2px 4px 8px #e6f4ff;
    width: 800px;
    margin: 0 auto;
    position: relative;
}

.user-avatar {
    margin-bottom: 20px;
}

.user-form {
    width: 100%;
}

.edit-button {
    position: absolute;
    top: 20px;
    right: 20px;
}
</style>